package com.put.mybills;


import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.put.mybills.adapter.GlobalParams;
import com.put.mybills.cloud.CreateAppDirectory;
import com.put.mybills.cloud.RecoverAppDirectory;
import com.put.mybills.cloud.SynchronizeAppData;
import com.put.mybills.cloud.SynchronizeBillPictures;
import com.put.mybills.cloud.SynchronizeFactureIcon;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * An abstract activity that handles authorization and connection to the Drive
 * services.
 */

public abstract class BaseDriveActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
	
	
    private static final String TAG = "BaseDriveActivity";

    /**
     * Extra for account name.
     */
    protected static final String EXTRA_ACCOUNT_NAME = "account_name";

    /**
     * Request code for auto Google Play Services error resolution.
     */
    protected static final int REQUEST_CODE_RESOLUTION = 1;

    /**
     * Next available request code.
     */
    protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;

    /**
     * Google API client.
     */
    public static GoogleApiClient mGoogleApiClient;

    /**
     * Selected account name to authorize the app for and authenticate the
     * client with.
     */
    protected String mAccountName;

    /**
     * Called on activity creation. Handlers {@code EXTRA_ACCOUNT_NAME} for
     * handle if there is one set. Otherwise, looks for the first Google account
     * on the device and automatically picks it for client connections.
     */
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        
        //deleteSharedPreferences();
        
        if (b != null) {
            mAccountName = b.getString(EXTRA_ACCOUNT_NAME);
        }
        if (mAccountName == null) {
            mAccountName = getIntent().getStringExtra(EXTRA_ACCOUNT_NAME);
        }

        if (mAccountName == null) {
            Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
            if (accounts.length == 0) {
                Log.d(TAG, "Must have a Google account installed");
                return;
            }
            mAccountName = accounts[0].name;
        }
    
    }

    /**
     * Saves the activity state.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(EXTRA_ACCOUNT_NAME, mAccountName);
    }

    /**
     * Called when activity gets visible. A connection to Drive services need to
     * be initiated as soon as the activity is visible. Registers
     * {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
     * activities itself.
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mAccountName == null) {
            return;
        }
        if (mGoogleApiClient == null) {
            // TODO: Don't set account name explicitly and remove required
            // permissions to query available accounts.
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API).addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER) 
                    .setAccountName(mAccountName).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
        }
        if (isNetworkAvailable()) 
        	mGoogleApiClient.connect();
    }

    /**
     * Handles resolution callbacks.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
        	if (isNetworkAvailable())
            	mGoogleApiClient.connect();
        }
    }
    
    private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}


    /**
     * Called when activity gets invisible. Connection to Drive service needs to
     * be disconnected as soon as an activity is invisible.
     */
    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    /**
     * Called when {@code mGoogleApiClient} is connected.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "GoogleApiClient connected");     
        detectIfApplicationStructureExsist();
       
    }

    /**
     * Called when {@code mGoogleApiClient} is disconnected.
     */
    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "GoogleApiClient connection suspended");
    }

    /**
     * Called when {@code mGoogleApiClient} is trying to connect but failed.
     * Handle {@code result.getResolution()} if there is a resolution is
     * available.
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
        if (!result.hasResolution()) {
            //GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
            return;
        }
        try {
            result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        } catch (SendIntentException e) {
            Log.e(TAG, "Exception while starting resolution activity", e);
        }
    }
    
    
    public void deleteSharedPreferences() {
    	
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); 
    	SharedPreferences.Editor editor = sharedPref.edit();
    	editor.clear();
    	editor.commit();
    	Log.d(TAG,"SharedPrefrence cleared");
    	
    	String appDataDir = sharedPref.getString(GlobalParams.getInstance().app_folder_name_sp, "");
    	Log.d(TAG, "app_folder_name_sp is " + appDataDir );
    	
    }
    
    public void detectIfApplicationStructureExsist() {
    	
    	
    	/*SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = sharedPref.edit();
    	editor.clear();
    	editor.commit();
    	Log.d(TAG,"SharedPrefrence cleared");
    	return;
    	*/
    	/*
    	SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = sharedPref.edit();
    	Integer ifFirstRun = sharedPref.getInt(GlobalParams.getInstance().app_fr_counter, 0);
    	if (ifFirstRun >= 0 && ifFirstRun<=4) {
    		Log.d(TAG,"Checking recovery structure");
	    	String appDataDir = sharedPref.getString(GlobalParams.getInstance().app_folder_name_sp, "");
	    	if (appDataDir.equals("")) {
	    		FindFiles cd = new FindFiles(mGoogleApiClient,getBaseContext());
	    		cd.setEvent(new RecoverAppDirectory(sharedPref,GlobalParams.getInstance().app_folder_name_sp));
	    		cd.findFiles(GlobalParams.getInstance().app_folder_name , "", GlobalParams.getInstance().app_folder_name_sp ,"text/plain");
	    	}
	    	else {    		
	    		
	    		String billDataDir = sharedPref.getString(GlobalParams.getInstance().bill_picture_dir_sp, "");
	    		if (billDataDir.equals("")) {
	    			FindFiles cd = new FindFiles(mGoogleApiClient,getBaseContext());
	        		cd.setEvent(new RecoverAppDirectory(sharedPref,GlobalParams.getInstance().bill_picture_dir_sp));
	        		cd.findFiles(GlobalParams.getInstance().bill_picture_dir,appDataDir, GlobalParams.getInstance().bill_picture_dir_sp, "text/plain");
	    		}
	    		
	 
	    		String factureDataDir = sharedPref.getString(GlobalParams.getInstance().facture_icon_dir_sp, "");
	    		if (factureDataDir.equals("")) {
	    			FindFiles cd = new FindFiles(mGoogleApiClient,getBaseContext());
	        		cd.setEvent(new RecoverAppDirectory(sharedPref,GlobalParams.getInstance().facture_icon_dir_sp));
	        		cd.findFiles(GlobalParams.getInstance().facture_icon_dir,appDataDir,GlobalParams.getInstance().facture_icon_dir_sp , "text/plain");
	    		}
	    		
	    		
	    		String dataDataDir = sharedPref.getString(GlobalParams.getInstance().app_data_dir_sp, "");
	    		if (dataDataDir.equals("")) {
	    			FindFiles cd = new FindFiles(mGoogleApiClient,getBaseContext());
	        		cd.setEvent(new RecoverAppDirectory(sharedPref,GlobalParams.getInstance().app_data_dir_sp));
	        		cd.findFiles(GlobalParams.getInstance().app_data_dir,appDataDir, GlobalParams.getInstance().app_data_dir_sp , "text/plain");
	    		}			
	    	}	
    	}
    	else {
    	*/
    		
    		//checkApplicationData(getBaseContext());  
    		createDirectoryStructure();
    		//deleteSharedPreferences();
    	/*}*/
    	
    	
    }
    
    public void createDirectoryStructure() {
    	
    	final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); 
		Thread t = new Thread(new Runnable() {
	        public void run() {		        	
	        	Log.d(TAG, "Create directory structure check");	        	
	        	String appDataDir = sharedPref.getString(GlobalParams.getInstance().app_folder_name_sp, "");
	        	Log.d(TAG, "app_folder_name_sp is " + appDataDir );
		    	if (appDataDir.equals("")) {
		    		CreateDirectoryBlock cd = new CreateDirectoryBlock(mGoogleApiClient);
		    		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().app_folder_name_sp));
		    		if (cd.createFolder(GlobalParams.getInstance().app_folder_name , "") == true ) {
		    			
		    			String billDataDir = sharedPref.getString(GlobalParams.getInstance().bill_picture_dir_sp, "");
			    		if (billDataDir.equals("")) {			    		
			        		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().bill_picture_dir_sp));
			        		cd.createFolder(GlobalParams.getInstance().bill_picture_dir,appDataDir);
			    		}			    		
			    		
			    		String factureDataDir = sharedPref.getString(GlobalParams.getInstance().facture_icon_dir_sp, "");
			    		if (factureDataDir.equals("")) {			    			
			        		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().facture_icon_dir_sp));
			        		cd.createFolder(GlobalParams.getInstance().facture_icon_dir,appDataDir);
			    		}
		    			
			    		
			    		String dataDataDir = sharedPref.getString(GlobalParams.getInstance().app_data_dir_sp, "");
			    		if (dataDataDir.equals("")) {			    			
			        		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().app_data_dir_sp));
			        		cd.createFolder(GlobalParams.getInstance().app_data_dir,appDataDir);
			    		}    			
		    		}
		    	}  	
	        }
		});
		t.start();
    }
    
    
    public void checkApplicationData(Context context) {
    	
    	
    	/*Integer ifFirstRun = sharedPref.getInt(GlobalParams.getInstance().app_fr_counter, -1);
    	
    	if (ifFirstRun==-1) {    	
	    */	
    		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);  
    	
    		String appDataDir = sharedPref.getString(GlobalParams.getInstance().app_folder_name_sp, "");
	    	if (appDataDir.equals("")) {
	    		CreateDirectory cd = new CreateDirectory(mGoogleApiClient,context);
	    		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().app_folder_name_sp));
	    		cd.createFolder(GlobalParams.getInstance().app_folder_name , "");
	    		
	    	}
	    	else {    		
	    	
    		
	    		String billDataDir = sharedPref.getString(GlobalParams.getInstance().bill_picture_dir_sp, "");
	    		if (billDataDir.equals("")) {
	    			CreateDirectory cd = new CreateDirectory(mGoogleApiClient,context);
	        		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().bill_picture_dir_sp));
	        		cd.createFolder(GlobalParams.getInstance().bill_picture_dir,appDataDir);
	    		}
	    		
	 
	    		String factureDataDir = sharedPref.getString(GlobalParams.getInstance().facture_icon_dir_sp, "");
	    		if (factureDataDir.equals("")) {
	    			CreateDirectory cd = new CreateDirectory(mGoogleApiClient,context);
	        		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().facture_icon_dir_sp));
	        		cd.createFolder(GlobalParams.getInstance().facture_icon_dir,appDataDir);
	    		}
	    		
	    		
	    		String dataDataDir = sharedPref.getString(GlobalParams.getInstance().app_data_dir_sp, "");
	    		if (dataDataDir.equals("")) {
	    			CreateDirectory cd = new CreateDirectory(mGoogleApiClient,context);
	        		cd.setEvent(new CreateAppDirectory(sharedPref,GlobalParams.getInstance().app_data_dir_sp));
	        		cd.createFolder(GlobalParams.getInstance().app_data_dir,appDataDir);
	    		}
	    		
	    		if (!appDataDir.equals("") && !billDataDir.equals("") && !factureDataDir.equals("") && !dataDataDir.equals(""))
	    			synchronizeApplicationData();
				
	    	}
    	
    
    }
    
    public void synchronizeApplicationData() {
    	
    	Log.d(TAG, "Synchronize all data via service");
    	
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); 
		String appDataDir = sharedPref.getString(GlobalParams.getInstance().app_data_dir_sp, "");
		Log.d(TAG, "AppDataDir is " + appDataDir);
		if (!appDataDir.equals(""))
			new SynchronizeAppData(null).synchronizeAppData(appDataDir,null,getResources().getString(R.string.cloud_data_store));
    
		
		String billDataDir = sharedPref.getString(GlobalParams.getInstance().bill_picture_dir_sp, "");
		Log.d(TAG, "billDataDir is " + billDataDir);
		if (!billDataDir.equals(""))
			new SynchronizeBillPictures(null).synchronizeIcon(billDataDir,null,getResources().getString(R.string.cloud_bill_stored));
		
		
		  
		String factureDataDir = sharedPref.getString(GlobalParams.getInstance().facture_icon_dir_sp, "");
		Log.d(TAG, "factureDataDir is " + factureDataDir);
		if (!factureDataDir.equals(""))
			new SynchronizeFactureIcon(null).synchronizeIcon(factureDataDir,null,getResources().getString(R.string.cloud_facture_store));
		
    
    }
    
    
    
    
}